package com.dogcatfishdish.containers
{
	import flash.display.DisplayObject;
	import uk.co.misterbenn.errors.ScreenManagerError;
	
	public class Screen implements IScreen
	{
		protected var _context:IScreenManager;
		protected var _object:*;
		protected var _onInitialise:*;
		protected var _onReset:*;
		protected var _onRemove:*;
		
		public function set context(context:IScreenManager):void
		{
			_context = context;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function set onInitialise(func:*):void
		{
			_onInitialise = func;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function set onAdd(func:*):void
		{
			_onReset = func;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function set onRemove(func:*):void
		{
			_onRemove = func;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function set content(object:*):void
		{	
			_object = object;
		}
		
		/**
		 * @inheritDoc
		 */	
		public function get content():DisplayObject
		{
			if(_object is Class)
			{
				_object = createDisplayObject(_object);
				init();
			}
			
			return _object;
		}	
		
		/**
		 * Constructor 
		 * @param content
		 * 
		 */		
		public function Screen(content:* = null)
		{
			this.content = content;
		}
	
		/**
		 * @inheritDoc
		 */	
		public function remove():void
		{
			if(_onRemove != null)
				applyCallback(_onRemove);
		}
		
		/**
		 * @inheritDoc
		 */	
		public function add():void
		{
			if(_onReset != null)
				applyCallback(_onReset);
		}
		
		
		// protected methods
		protected function createDisplayObject(clazz:Class):*
		{
			var obj:* = new clazz();
			
			checkType(obj);
			
			return obj;
		}
		
		protected function checkType(obj:*):void
		{
			if(!(obj is DisplayObject))
				throw new ScreenManagerError(obj + ScreenManagerError.WRONG_TYPE);
		}
		
		protected function init():void
		{
			if(_onInitialise != null)
				applyCallback(_onInitialise);
		}
		
		protected function applyCallback(func:*):void
		{
			if(func is Function)
			{
				func.apply(null);
			}
			else
			{
				if(!_object.hasOwnProperty(func))
					throw new ScreenManagerError(ScreenManagerError.NO_CALLBACK);
				
				_object[func].apply(null);
			}
		}
	}
}